<?php

namespace frontend\controllers;

use Yii;
use frontend\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\components\MTools;

/**
 * Site controller
 */
class SiteController extends Controller {

    public $message = "";
    public $flag = false;

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post', 'get'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex() {
        if (Yii::$app->user->isGuest) {
            $this->redirect(["login"]);
        }

        return $this->render('index');
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin() {
        $this->layout = FALSE;
        $model = new LoginForm();
        if (Yii::$app->request->isAjax) {
            $model->username = Yii::$app->request->post("txtUserName");
            $model->password = Yii::$app->request->post("txtPassword");
            if ($model->login()) {
                echo json_encode(["status" => 1, "url" => \yii\helpers\Url::toRoute(["index"])]);
            } else {
                foreach ($model->errors as $errors) {
                    $message = $errors[0];
                    break;
                }
                echo json_encode(["status" => false, "msg" => $message]);
            }
            exit();
        }
        return $this->render('login', [ 'model' => $model]);
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout() {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact() {
        return $this->render("contact");
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout() {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup() {
        $this->layout = false;
        $model = new SignupForm();
        $invite_code = Yii::$app->request->get("id");
        if (Yii::$app->request->isAjax) {
            $model->phone = Yii::$app->request->post("phone");
            $model->username = Yii::$app->request->post("username");
            $model->password = Yii::$app->request->post("password");
            $model->repassword = Yii::$app->request->post("repassword");
            $model->invite_code = Yii::$app->request->post("invite_code");
            $model->truename = Yii::$app->request->post("truename");
            $model->alipay = Yii::$app->request->post("alipay");
            $model->qq = Yii::$app->request->post("qq");
            $event = new \common\components\TaskEvent();
            $this->on("add_register", [$event, "addRegisterEvent"], [
                "taskmoney" => 0,
                "type" => 1,
                "class_type" => 1,
                "model" => $model
            ]);
            $this->trigger("add_register", $event);
            $this->off("add_register");
            echo json_encode(["status" => $this->flag, "msg" => $this->message, "url" => \yii\helpers\Url::toRoute(["index"])]);
            exit();
        }
        return $this->render('signup', [ 'model' => $model,"invite_code"=>$invite_code]);
    }

    /*
     * 检测登陆状态
     */

    public function actionLoginstatus() {
        if (!\Yii::$app->user->isGuest) {
            echo json_encode(["status" => true]);
        } else {
            echo json_encode(["status" => false]);
        }
    }

    /*
     * 检测手机号是否已经注册
     */

    public function actionSubmitregajax() {
        $action = Yii::$app->request->get("action");
        if ($action === "username") {
            $model = new \common\models\User();
            $valid = new \yii\validators\UniqueValidator();
            $model->username = Yii::$app->request->post("param");
            $valid->validateAttribute($model, "username");
            if ($model->errors) {
                echo json_encode(["status" => 'n', 'info' => "该用户名已被注册"]);
            } else {
                echo json_encode(["status" => 'y', 'info' => "该用户名可用"]);
            }
        } else if ($action === "validate_invitation") {
            $invite_code = Yii::$app->request->post("param");
            if (preg_match('/^Y[0-9]{5}$/', $invite_code)) {
                if ($invite_code !== MTools::getYiiParams("sys_invite_code")) {
                    $model = \common\models\User::find()->where("my_code=:invite_code", [":invite_code" => $invite_code])->one();
                    if ($model instanceof \common\models\User && $model->role == 1) { //说明邀请码存在
                        echo json_encode(["status" => 'y', 'info' => "该邀请码可用"]);
                    } else {
                        echo json_encode(["status" => 'n', 'info' => "该邀请码不可用"]);
                    }
                } else {
                    echo json_encode(["status" => 'y', 'info' => "该邀请码可用"]);
                }
            } else {
                echo json_encode(["status" => 'n', 'info' => "该邀请码格式不正确"]);
            }
        } else if ($action === "validate_alipay") {
            $alipay = Yii::$app->request->post("param");
            $emailpattern = '/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/';
            $phonepattern = '/^((0\\d{2,3}(-){0,1}\\d{7,8})|(1[3584]\\d{9}))$/';
            if (preg_match($emailpattern, $alipay) || preg_match($phonepattern, $alipay)) {
                echo json_encode(["status" => 'y', 'info' => "该支付宝可用"]);
            } else {
                echo json_encode(["status" => 'n', 'info' => "支付宝账号只能输入邮箱和手机号码！"]);
            }
        }
    }

    /*
     * 发送手机验证码
     */

    public function actionSendcode() {
        echo json_encode(["status" => true, 'msg' => "验证码发送成功"]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset() {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
                    'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetpassword($token) {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
                    'model' => $model,
        ]);
    }

    public function actionFrost() {
        $message = "";
        $frostmodel = \backend\models\MY_UserFrostRecord::find()->where("userid=:userid", [":userid" => Yii::$app->user->id])->orderBy("created_at desc")->one();
        if ($frostmodel instanceof \backend\models\MY_UserFrostRecord) {
            $message = $frostmodel->note;
        }
        return $this->render("frost", ["message" => $message]);
    }

}
